package org.nativejpa.query;

import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * used to close connection if no transaction, so connection can return to pool
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 * @create 2009-3-18 14:43:10
 */
public class ConnectionQuerySynchronization implements QuerySynchronization {
    static Log logger = LogFactory.getLog(ConnectionQuerySynchronization.class);

    public void beforeExecuteQuery(SQLQuery query) {
    }

    public void beforeExecuteUpdate(SQLQuery query) {

    }

    public void afterExecuteQuery(SQLQuery query, boolean success) {
        // Try close connection if no transaction, so connection can return to pool
        if(!query.getEntityManager().getEntityManagerFactory().getEntityTransaction().isActive()) {
            try {
                query.closeConnection();
            }
            catch (SQLException e) {
                // should no Exception
                e.printStackTrace();
            }
        }
    }

    public void afterExecuteUpdate(SQLQuery query, boolean success) {
        afterExecuteQuery(query,success);
    }

}